package com.mohe.shanpao.controller.user;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.mohe.shanpao.controller.BaseController;

/**
 * 
 * @author  徐磊
 * @version  [版本号, 2016年7月4日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */

@Controller
public class LoginController extends BaseController
{
	private final static Logger logger = LoggerFactory.getLogger(LoginController.class);
	
    /**
     * 用户登录验证
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("/doLogin")
    @ResponseBody
    public Map<String, Object> login(String name, String password, String code, HttpServletRequest request)
    {
        Map<String, Object> data = new HashMap<String, Object>();
        boolean success = true;
        String msg = "登录成功";
        try
        {
        	UsernamePasswordToken token = new UsernamePasswordToken(name,password);
            // 获取当前的Subject
            Subject currentUser = SecurityUtils.getSubject();
            currentUser.login(token);
            
            logger.info("用户 "+ name +" 登录成功 ");
        }
        catch (UnknownAccountException e)
        {
            success = false;
            msg = "用户名或密码错误";
        }
        catch (IncorrectCredentialsException e)
        {
            success = false;
            msg = "用户名或密码错误";
        }
        
        data.put("success", success);
        data.put("msg", msg);
        return data;
    }
    
    /**
     * 
     * 用户登出
     * <功能详细描述>
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("/logout")
    public ModelAndView logout()
    {
        try
        {
            // 获取当前的Subject
            Subject currentUser = SecurityUtils.getSubject();
            logger.info("用户 "+ currentUser.getPrincipal() +" 登出成功 ");
            
            currentUser.logout();
        }
        catch (Exception e)
        {
            logger.error("登出异常 : " + e.getMessage());
        }
        
        return new ModelAndView("redirect:login.html");
    }

    
}
